package cn.schoolwow.quickdao.module.database.dml.instance.service;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteUpdateConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class TruncateTableFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        String tableName = (String) flowContext.checkData("tableName");
        DatabaseProvider databaseProvider = quickDAOConfig.databaseContext.databaseProvider;

        switch (databaseType){
            case SQLite:{
                flowContext.broken("SQLite数据不支持Truncate操作");
            }break;
            case Postgresql:{
                flowContext.putTemporaryData("sql", "truncate table " + databaseProvider.escape(tableName) + " restart identity cascade;");
            }break;
            default:{
                flowContext.putTemporaryData("sql", "truncate table " + databaseProvider.escape(tableName));
            }break;
        }
        flowContext.startFlow(new ExecuteUpdateConnectionFlow())
                .putTemporaryData("name", "清空表")
                .execute();
    }

    @Override
    public String name() {
        return "清空表";
    }
}
